<template>
  <view class="userInfo-container">
    <uni-forms ref="userInfoRef" :model="userInfoForm" :rules="userInfoRules">
      <uni-forms-item name="images">
        <uni-file-picker
          limit="1"
          title="最多选择1张图片"
          fileMediatype="image"
          @select="imageSelect"
          @delete="imagesDelete"
          v-model="userInfoForm.images"
          return-type="array"
        ></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item label="个人简介:" name="introduction" label-width="85">
        <uni-easyinput
          type="textarea"
          v-model="userInfoForm.introduction"
          placeholder="请输入个人简介"
        ></uni-easyinput>
      </uni-forms-item>
      <view class="form-btn-container">
        <button @click="userInfoSubmit" class="submit-btn">修改个人信息</button>
      </view>
    </uni-forms>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { useUserStore } from "@/stores";
import { updateUserInfoParams } from "@/types/user";
import { handleCoverToImageList } from "@/utils/vote";
import { modifyUserInfoAPI } from "@/api/user";

const userStore = useUserStore();
const userInfoForm: updateUserInfoParams = reactive({
  avatar: userStore.userInfo!.avatar,
  introduction: userStore.userInfo!.introduction,
  images: handleCoverToImageList(userStore.userInfo!.avatar),
});

const userInfoRules: UniHelper.UniFormsRules = {
  images: {
    rules: [{ required: true, errorMessage: "请上传选手图片" }],
  },
  introduction: {
    rules: [
      {
        required: true,
        errorMessage: "请输入个人简介",
      },
      { maxLength: 30, errorMessage: "个人简介不能超过30个字符" },
    ],
  },
};
const userInfoRef = ref<UniHelper.UniFormsInstance>();

//选手
const imageSelect: UniHelper.UniFilePickerOnSelect = (event: any) => {
  const imageDatas = event.tempFiles.map((item: any) => {
    return { url: item.url, name: item.name };
  });
  userInfoForm.images.push(...imageDatas);
};

const imagesDelete: UniHelper.UniFilePickerOnDelete = (event: any) => {
  userInfoForm.images.splice(event.index, 1);
};

const userInfoSubmit = async () => {
  await userInfoRef.value?.validate?.();
  await modifyUserInfoAPI(userInfoForm);
  uni.showToast({
    title: "修改成功",
    icon: "success",
    duration: 1000,
  });
  userStore.setUserInfo();
};
</script>
<style scoped lang="scss">
.userInfo-container {
  padding: 20px;
  .form-btn-container {
    display: flex;
    justify-content: space-between;

    .submit-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 500rpx;
      background-color: #2979ff;
      height: 80rpx;
      font-size: 28rpx;
      border-radius: 8rpx;
      color: #fff;
    }
  }
}
</style>
